package com.example.sikong.handler.scheduled;

import com.example.sikong.dto.LiveContainerResultDTO;
import com.example.sikong.dto.SiKongResult;
import com.example.sikong.entity.SkDeviceConfig;
import com.example.sikong.feign.SiKongApiClient;
import com.example.sikong.service.ISkDeviceConfigService;
import com.example.sikong.service.RedisProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
@Slf4j
public class ScheduledTasks {
    @Autowired
    ISkDeviceConfigService skDeviceConfigService;
    @Autowired
    private SiKongApiClient siKongApiClient;
    @Value("${si-kong.orgSecret}")
    private String orgSecret;
    @Autowired
    private RedisProvider redisProvider;

    /*停止所有直播开始*/
    @Scheduled(cron = "*/33 * * * * ?")
    public void exec() {
        log.info("兜底定时任务，停止所有直播");
        List<SkDeviceConfig> list = skDeviceConfigService.list();
        for (SkDeviceConfig skDeviceConfig : list) {
            String sn = skDeviceConfig.getSn();
            String camera = skDeviceConfig.getCamera();

            SiKongResult<LiveContainerResultDTO> liveContainer = siKongApiClient.getLiveContainer(orgSecret, String.join("_", sn, camera));
            LiveContainerResultDTO data = liveContainer.getData();
            if (data == null || data.getTotal_count() == 0) {
                return;
            }
            List<LiveContainerResultDTO.ContainerDTO> members = data.getMembers();
            for (LiveContainerResultDTO.ContainerDTO member : members) {
                if (member.isValidate()) {
                    try {
                        String converterId = member.getConverter_id();
                        //redis 存在该路播流
                        if (!Objects.isNull(redisProvider.get(converterId))) {
                            log.info("本路直播还在进行，不关闭：" + converterId);
                            continue;
                        }
                        siKongApiClient.stopLive(orgSecret, converterId);
                        log.info("已关闭直播：" + converterId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
